global class ContractWebService {

    /*
    *
    * 同步到OA 发起审批流
    * conid 合同Id 
    * workflowId  385
    * 
    */

   /* public static Map<String,Map<String,String> > getFieldsMap(){

        Map<String ,String > fields = new Map<String,String>();
        fields.put('单一', '0');
        fields.put('打包多项目', '1');
        fields.put('', '');
        fields.put('', '');
        fields.put('', '');
        fields.put('', '');
        fields.put('', '');
        fields.put('', '');
        fields.put('', '');
        fields.put('', '');
        fields.put('', '');

    }*/

    /*
     WebService static String postOA(String conid ){

          return postToOA(conid,false);

     }
    WebService static String postToOA(String conid , Boolean isUnContract){


        Map<String,String> mainMap = new Map<String,String>();
        //1.获取人员的OA id 

        Contract__c  con = [select RecordType.DeveloperName,ApproveType__c,MainContract__c,MainContract__r.ProcessID__c ,TerminalCustomer__r.Name ,

         Account__r.RecordType.DeveloperName , Status__c,ProcessID__c, ContractURL__c,CooperationType__c,Account__r.Name ,ContractSource__c,

        isSycToOa__c,Id ,Maccura__c, Maccura__r.AccountNumber,CustomerContact__r.Name , CustomerPhone__c ,Vsalestrucode__c,

        Corpcode__c,CustomerContact__c

         from Contract__c where Id =:conid];

        if(con == null)return '合同错误!不能发起OA流程!';

        Boolean isMainContract = con.RecordType.DeveloperName == 'TerminalContract';

        Boolean isBlankMainContract  = con.MainContract__c == null ;


        if(!isUnContract && (con.Status__c == '已生效'|| con.Status__c == '已终止')) return '合同'+con.Status__c +'!不能发起OA流程';
        
        if( !isUnContract &&  con.IsSycToOa__c == true) return '已同步OA不要重复同步!';

        if(con.ApproveType__c == null  )return '合同签订类型不能为空!';

        if(con.ContractSource__c == null  )return '合同签订类型不能为空!';

        if(con.CooperationType__c == null  )return '合同审批类型不能为空!';

         String workflowId = isMainContract ? '1563' : '1564';

         System.debug('ContractWebService==>'+workflowId);

        if(!isMainContract && isBlankMainContract) return '主合同不能为空!';


        if(!isMainContract && String.isBlank(con.MainContract__r.ProcessID__c)  ) return 'OA合同流程ID不能空!';

        if(!isMainContract && con.RecordType.DeveloperName == 'ContractChange' && con.Status__c == 'SF审批成功' ) return '补充变更合同必须SF审批通过才能推送 ' ;

         try {
              Integer.valueOf(con.CooperationType__c);
          }
          catch (Exception e) {
              
              return '合同类型异常值!';
          }
            Contract__c  mcon = new Contract__c();
            mcon.MainContract__c = con.Id;
            mcon.ContractSource__c = con.ContractSource__c;
            mcon.Vsalestrucode__c = con.Vsalestrucode__c;
            mcon.Corpcode__c = con.Corpcode__c;
            mcon.CooperationType__c = con.CooperationType__c;
            mcon.Account__c = con.Account__c;
            mcon.Maccura__c = con.Maccura__c;
            mcon.CustomerContact__c = con.CustomerContact__c;
            mcon.RecordTypeId = Utils.getRecordTypeIdByDevNameAndObjName('DeleteContract', 'Contract__c');


        //if(con.Account__r.RecordType.DeveloperName == 'Dealer' && is. con.Account__r.DealerType__c == ) return con.Account__r.Name + '经销商类型不能为空!';

        User u = [select Id, EmployeeNumber from User  where Id =: UserInfo.getUserId()];
        if(u.EmployeeNumber == null) return '请维护合同创建人的工号!'; 

        String emNumber = null ;

        try {
           emNumber =  u.EmployeeNumber.replaceFirst('^0+', '');
        }catch (Exception e) {
            return '解析发起审批人工号错误:'+e.getMessage();
        }
         try {
            Integer.valueOf(con.ApproveType__c);
        }
        catch (Exception e) {
            
            return '合同签定类型异常值!';
        }
         try {
            Integer.valueOf(con.ContractSource__c);
        }
        catch (Exception e) {
            
            return '合同来源异常值!';
        }
        if(con.Maccura__c == null) return '我方主体必填!';
        if(con.Maccura__r.AccountNumber == null || con.Maccura__r.AccountNumber =='' )return '请维护我方主体的客户编码!';

        //webservicesTcWeaverComCn.TranscodingServiceHttpPort wwc = new webservicesTcWeaverComCn.TranscodingServiceHttpPort();
        // String subcompanyid  = null;
         if(Test.isRunningTest()){
            // Test.setMock(WebServiceMock.class, new FWOATCWebserviceMockImpl());
             // subcompanyid = '111';
          }else{
           // subcompanyid = wwc.CompanyTrans(con.Maccura__r.AccountNumber);
             
          }

          if([select count() from Contract__c where MainContract__c =:con.Id and RecordType.DeveloperName = 'DeleteContract' ] > 0 ) return '已经存在解约合同!';


          if(isUnContract)insert mcon;
       //请求Hr数据，获取系统内ID
        HttpRequest request = new HttpRequest();
        request.setMethod('GET');
        request.setEndpoint(Label.GetOAPersonCode+'?userID='+emNumber);
        HttpResponse res=  Utils.postRequest(request,2);


         if (res.getStatusCode() == 200) {
                Map<String,Object> r = new Map<String,Object>();
                //如果是测试
                if(Test.isRunningTest()){

                    Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','<UserBean-array>  <UserBean>    <userid>4854</userid>    <subcompanyid1>126</subcompanyid1>    <departmentid>3009</departmentid>    <subcompanyname>迈克电子</subcompanyname>    <departmentname>四川</departmentname>    <workcode>2896</workcode>    <lastname>文明红</lastname>    <loginid>2896</loginid>    <password>E547BF53F93AD2A0027F8F54FE28EE95</password>    <seclevel>20</seclevel>    <sex>女</sex>    <jobtitle>449</jobtitle>    <jobcall></jobcall>    <joblevel>17</joblevel>    <jobactivitydesc></jobactivitydesc>    <managerid>4848</managerid>    <assistantid></assistantid>    <status>1</status>    <locationid>21</locationid>    <workroom></workroom>    <telephone>81694</telephone>    <mobile>15882203634</mobile>    <mobilecall></mobilecall>    <fax></fax>    <email>wenminghong@maccura.com</email>    <systemlanguage></systemlanguage>    <birthday></birthday>    <folk></folk>    <nativeplace></nativeplace>    <regresidentplace></regresidentplace>    <certificatenum></certificatenum>    <maritalstatus>未婚</maritalstatus>    <policy></policy>    <bememberdate></bememberdate>    <bepartydate></bepartydate>    <islabouunion></islabouunion>    <educationlevel></educationlevel>    <degree></degree>    <healthinfo></healthinfo>    <height></height>    <weight></weight>    <residentplace></residentplace>    <homeaddress></homeaddress>    <tempresidentnumber></tempresidentnumber>    <startdate>2016-12-05</startdate>    <enddate>2900-01-01</enddate>    <createdate>2018-07-13</createdate>    <lastChangdate>2018-08-03</lastChangdate>    <accounttype>0</accounttype>    <dsporder>4983.0</dsporder>  </UserBean></UserBean-array>');
                    r =  resBody;
                }else{
                     r  = (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }
                 if(r.get('code') == 0 || r.get('code') == '0'){
                
                   if (r.get('result') != null ) {
                      String jsr = (String)r.get('result');
                        //格式化
                      Pattern p = Pattern.compile('\\s*|\t|\r|\n');
                      Matcher m_jsr = p.matcher(jsr);
                      String n_jsr = m_jsr.replaceAll('');
                      //String xml_o = n_jsr.replace('<UserBean-array>', '');
                      //String n_xml = xml_o.replace('</UserBean-array>', '');
                     // System.debug(n_xml);
                      //XML解析
                      Dom.Document doc = new Dom.Document(); 
                      doc.load(n_jsr);

                      Dom.XMLNode userDataInfo = doc.getRootElement();

                      String userid = '';
                      String subcompanyid1 = '';
                      String departmentid = '';

                      for(Dom.XMLNode node : userDataInfo.getChildren()){

                          if(node.getChildElement('status',null ).getText() != '5'){

                            userid = node.getChildElement('userid', null).getText(); 
                            subcompanyid1= node.getChildElement('subcompanyid1', null).getText();
                            departmentid = node.getChildElement('departmentid', null).getText();
                            break;
                          }
                      }

                     
                      mainMap.put('sqr',userid);//申请人;
                      mainMap.put('ssbm',departmentid);//所属部门;
                      mainMap.put('ssgs',subcompanyid1);//所属公司;
                     // mainMap.put('htmc',);//合同名称;
                    // if(subcompanyid != null ) mainMap.put('wfzt',subcompanyid);//我方主体;

                      mainMap.put('htsplx','0');//合同类型
                        
                      mainMap.put('ej',con.CooperationType__c);//二级分类(合同审批类型) 0 单一 1 打包多项目  2 三方机构集团类合同  3 三方机构非集团类合同
                      mainMap.put('zxfx','0');//直销/分销
                      mainMap.put('sfxm','0');//是否项目
                      mainMap.put('sfwdbyw','1');//是否为代开业务
                      mainMap.put('htqx','0');//合同期限
                      mainMap.put('bz','0');//币种
                      mainMap.put('hthtje','0');//合同金额
                      

                      mainMap.put('htly',con.ContractSource__c);//合同来源  0 我方全模板 1 模板修改 2 非模板 

                      mainMap.put('fkfx','0');//付款方向

                     
                      mainMap.put('qdlx',con.ApproveType__c );//(合同签定类型) 0 签约 1 续签 2 补充变更 3 解约

                      mainMap.put('sfbh',conid);//合同编号

                      //主合同
                    // if(!isMainContract)mainMap.put('zhtbh', '10342');

                      //合同
                      //http://192.168.42.57:82/maccura/salesforce/TokenToSF_wev.jsp?flag=a0P0I00001J7vXvUAJ
                      mainMap.put('sfhtlj','<a href="http://192.168.42.57:82/maccura/salesforce/TokenToSF_wev.jsp?flag='+(isUnContract ? mcon.Id : con.Id ) +'">点击查看</a>');
                      
                      //mainMap.put('jxsjb',con.Account__r.DealerType__c);//合同编号
                    //  mainMap.put('htjg', '<a href=\'https://maccura.secure.force.com/inhome/ContractProductPDF?conid='+conid+'&type=2\' target=\'__blank\'>点击查看</a>');//签订类型

                      webservicesWorkflowWeaver1.WorkflowRequestInfo  wk = new webservicesWorkflowWeaver1.WorkflowRequestInfo ();

                      wk.requestName = '与'+con.Account__r.Name +'-'+con.TerminalCustomer__r.Name + '的销售合同审批';
                      wk.requestLevel = '0';
                      wk.creatorId = userid;
                        //流程基础信息
                      webservicesWorkflowWeaver1.WorkflowBaseInfo wbf = new webservicesWorkflowWeaver1.WorkflowBaseInfo();
                     // wbf.workflowId = '385';
                      //流程Id 
                      wbf.workflowId = workflowId;// Label.OAContractFlowID;

                      wbf.workflowName = '销售合同';
                      wbf.workflowTypeName = '销售合同';
                      wk.workflowBaseInfo = wbf;
                      webservicesWorkflowWeaver1.WorkflowMainTableInfo wmtf = new webservicesWorkflowWeaver1.WorkflowMainTableInfo();
                    //主表字段
                      webservicesWorkflowWeaver1.WorkflowRequestTableField[] wrtfs = genTableField(mainMap);
                      Map<String,String> detailMap = new Map<String,String>();
                      detailMap.put('htxdf', con.Account__r.Name );//合同相对方
                      detailMap.put('xdflxr', con.CustomerContact__r.Name );//合同相对方联系人
                      detailMap.put('xdflxfs', con.CustomerPhone__c);//合同相对方联系方式


                    //明细表字段
                      webservicesWorkflowWeaver1.WorkflowRequestTableField[] wrtfs_dt = genTableField(detailMap);

                     webservicesWorkflowWeaver1.WorkflowDetailTableInfo wfdti = new webservicesWorkflowWeaver1.WorkflowDetailTableInfo();
 
                      webservicesWorkflowWeaver1.ArrayOfWorkflowRequestTableField awrtf = new webservicesWorkflowWeaver1.ArrayOfWorkflowRequestTableField();
                      awrtf.WorkflowRequestTableField = wrtfs;

                      webservicesWorkflowWeaver1.WorkflowRequestTableRecord wrtr= new webservicesWorkflowWeaver1.WorkflowRequestTableRecord();
                      wrtr.workflowRequestTableFields = awrtf;
                      
                      webservicesWorkflowWeaver1.WorkflowRequestTableRecord[] wrtrs = new List<webservicesWorkflowWeaver1.WorkflowRequestTableRecord>();
                      wrtrs.add(wrtr);

                      webservicesWorkflowWeaver1.ArrayOfWorkflowRequestTableRecord awrtr = new webservicesWorkflowWeaver1.ArrayOfWorkflowRequestTableRecord();
                      awrtr.WorkflowRequestTableRecord =  wrtrs;

                      wmtf.requestRecords = awrtr;
                      wk.workflowMainTableInfo = wmtf;

                      webservicesWorkflowWeaver1.ArrayOfWorkflowRequestTableField awrtfdt = new webservicesWorkflowWeaver1.ArrayOfWorkflowRequestTableField();
                      awrtfdt.WorkflowRequestTableField = wrtfs_dt;

                      webservicesWorkflowWeaver1.WorkflowRequestTableRecord wrtrdt= new webservicesWorkflowWeaver1.WorkflowRequestTableRecord();
                      wrtrdt.workflowRequestTableFields = awrtfdt;

                      webservicesWorkflowWeaver1.WorkflowRequestTableRecord[] wrtrsdi = new List<webservicesWorkflowWeaver1.WorkflowRequestTableRecord>();
                      wrtrsdi.add(wrtrdt);

                      webservicesWorkflowWeaver1.ArrayOfWorkflowRequestTableRecord  awrtrdi = new webservicesWorkflowWeaver1.ArrayOfWorkflowRequestTableRecord();
                      awrtrdi.WorkflowRequestTableRecord = wrtrsdi;

                      wfdti.workflowRequestTableRecords =  awrtrdi;

                      webservicesWorkflowWeaver1.WorkflowDetailTableInfo[]  wfdtis = new List<webservicesWorkflowWeaver1.WorkflowDetailTableInfo>();
                      wfdtis.add(wfdti);

                      webservicesWorkflowWeaver1.ArrayOfWorkflowDetailTableInfo  awdti = new webservicesWorkflowWeaver1.ArrayOfWorkflowDetailTableInfo();
                      awdti.WorkflowDetailTableInfo = wfdtis;

                      wk.workflowDetailTableInfos = awdti;

                      String  requestId = '';
                      webservicesServicesWeaverComCn1.WorkflowServiceHttpPort wsh = new webservicesServicesWeaverComCn1.WorkflowServiceHttpPort();
                      if(Test.isRunningTest()){
                          webservicesWorkflowWeaver1.ArrayOfWorkflowRequestLog awr = new webservicesWorkflowWeaver1.ArrayOfWorkflowRequestLog();
                          webservicesWorkflowWeaver1.WorkflowRequestLog[]  wrls = new  List<webservicesWorkflowWeaver1.WorkflowRequestLog>();

                          webservicesWorkflowWeaver1.WorkflowRequestLog  wrl = new  webservicesWorkflowWeaver1.WorkflowRequestLog();
                          wrls.add(wrl);
                          awr.WorkflowRequestLog = wrls ;
                          wk.workflowRequestLogs = awr ;

                          Test.setMock(WebServiceMock.class, new FWOAWorkFlowWebserviceMockImpl());
                          requestId = '12345';
                      }else{
                        requestId= wsh.DoCreateWorkflowRequest(wk,Integer.valueOf(userid));
                          
                      }
                      


                      System.debug(requestId);
                      String  oaflowID  =  Integer.valueOf(requestId) > 0 ? requestId : null ;
                      String msg = returnMsg(requestId);
                      if(msg == '同步成功!'){
                        if(isUnContract){

                          mcon.isSycToOa__c = true;
                          mcon.ProcessID__c = oaflowID;
                          if(oaflowID != null ) con.ContractURL__c = 'https://fwoa.maccura.com/workflow/request/ViewRequest.jsp?requestid='+oaflowID+'&_workflowid=1085';
                          mcon.Status__c = '已推送OA';
                          update mcon;
                          Approval.lock(mcon,false);
                        }else{
                          con.isSycToOa__c = true;
                          con.ProcessID__c = oaflowID;
                          if(oaflowID != null ) con.ContractURL__c = 'https://fwoa.maccura.com/workflow/request/ViewRequest.jsp?requestid='+oaflowID+'&_workflowid=1085';
                          con.Status__c= '已推送OA';
                          update con;
                          Approval.lock(con,false);
                        }
                        
                      }else{
                        if(isUnContract)delete mcon;

                      }
                      
                      return msg ;
                   }else{
                      if(isUnContract)delete mcon;
                      return '调用OA接口报错!';
                   }
                }else{
                    if(isUnContract)delete mcon;
                   return '调用ESB接口报错!';
                } 
            } else {
                if(isUnContract)delete mcon;
                return '系统错误:'+res.toString()+',请联系系统管理员!';
            }
       
        //2.组装数据

        //3.发起流程
    }
    private static String returnMsg(string reqid ){
       Map<String,String>  msg = new Map<String,String>();
     
      msg.put('-1', 'OA创建流程失败');
      msg.put('-2', 'OA没有创建权限');
      msg.put('-3', 'OA创建流程失败');
      msg.put('-4', 'OA字段或表名不正确');
      msg.put('-5', 'OA更新流程级别失败');
      msg.put('-6', 'OA无法创建流程待办任务');
      msg.put('-7', 'OA流程下一节点出错，请检查流程的配置，在OA中发起流程进行测试');
      msg.put('-8', 'OA流程节点自动赋值操作错误');

      if(msg.get(reqid) == null){

         return '同步成功!';

      }else{

        return msg.get(reqid) ;

      }
    }
    private static webservicesWorkflowWeaver1.WorkflowRequestTableField[] genTableField(Map<String,String> tMap ){
       webservicesWorkflowWeaver1.WorkflowRequestTableField[] wrtfs = new List<webservicesWorkflowWeaver1.WorkflowRequestTableField>();

       for (String key : tMap.keySet() ) {
          webservicesWorkflowWeaver1.WorkflowRequestTableField wrtf0 = new webservicesWorkflowWeaver1.WorkflowRequestTableField();
          wrtf0.fieldName = key;
          wrtf0.fieldValue = tMap.get(key);
          wrtf0.edit = true;
          wrtf0.view = true;
          wrtfs.add(wrtf0);
       }
       return wrtfs;
    }

*/

    /*
    id 合同id 
    t 操作类型   1=新增  2=修改  3=删除 
    qt 报价类型   1=报价  2=调价
    */
    ///2018-01-02 全部同步为报价单
    // 调用NC接口
    /*
    WebService static String postQuote(Id id, String t, String qt) {
        

            Contract__c con = [select Id,NCTime__c from Contract__c where Id=:id];
            List<ContractProduct__c> cpList = [select Contract__r.OwnerId,
                                               Contract__r.Corpcode__c, Contract__r.Vsalestrucode__c, Contract__r.Account__r.AccountNumber, CreatedBy.Name,
                                                Contract__r.ContractNumber__c, Contract__r.LastModifiedDate, Contract__r.Owner.Name,
                                                Product__r.NCCode__c, SalesPrice__c,Contract__r.TerminalCustomer__r.NCICCode__c from ContractProduct__c
                                                where Contract__c = :id and IsSycToNc__c = false and DelContractProduct__c != true];
            if (cpList.size() == 0) {
                return 'NO DATA';
            }
            ContractProduct__c cp1  = cpList[0];
             User u = [select Id, Manager.Name from User where Id =:cp1.Contract__r.OwnerId];

                        ///后期处理数据不正常的问题
            List<ConProductArgs> conProductArgsList = new List<ConProductArgs>();
            
              for (ContractProduct__c cp : cpList) {
                ConProductArgs cpa = new ConProductArgs();
                cpa.corpcode = cp.Contract__r.Corpcode__c;  //公司编码
                cpa.custcode = cp.Contract__r.Account__r.AccountNumber ;  //客户编码
                cpa.vsalestrucode = cp.Contract__r.Vsalestrucode__c ; //销售组织编码
                cpa.created_by = cp.Contract__r.Owner.Name; //创建人名字
                cpa.sub_corp_manager = u.Manager.Name;  //报价的销售中心总监名字
                cpa.csourcecode = cp.Contract__r.ContractNumber__c; //合同自动编号
                cpa.ts = Utils.date2string(System.now()) ; //合同的lastmodifieddate
                cpa.cemployeecode = cp.Contract__r.Owner.Name; //所有者
                cpa.invcode = cp.Product__r.NCCode__c; //产品的NCCode__c
                cpa.dreceiptdate  = Utils.date2string(Date.valueOf(System.now()));//报价日期
                cpa.noriginalcurtaxprice = String.valueof(cp.SalesPrice__c)  ; //SalesPrice__c
                cpa.nitemdiscountrate = '100';//默认100
              //  cpa.nnumber = String.valueof(cp.Number__c);
                cpa.opertype = t; //操作类型   1=新增  2=修改  3=删除
                cpa.quotetype = qt; //报价类型   1=报价  2=调价
                cpa.csalequotationid = id;
                cpa.csalequotation_bid = cp.Id;
                cpa.addCustomer =cp.Contract__r.TerminalCustomer__r.NCICCode__c;
                conProductArgsList.add(cpa);
              }
           //if (qt == '1'){ }
        //    else if(qt == '2'){
        //       for (ContractProduct__c cp : cpList) {
        //         ConProductArgs cpa = new ConProductArgs();
        //         cpa.corpcode = cp.Contract__r.Corpcode__c;  //公司编码
        //         cpa.custcode = cp.Contract__r.Account__r.AccountNumber ;  //客户编码
        //         cpa.vsalestrucode = cp.Contract__r.Vsalestrucode__c ; //销售组织编码
        //         cpa.created_by = cp.CreatedBy.Name; //创建人名字
        //         cpa.sub_corp_manager = cp.Contract__r.BranchOfficeManager__r.Name;  //报价的销售中心总监名字
        //         cpa.csourcecode = cp.Contract__r.ContractNumber__c; //合同自动编号
        //         cpa.ts = Utils.date2string(cp.Contract__r.LastModifiedDate) ; //合同的lastmodifieddate
        //         cpa.cemployeecode = cp.Contract__r.Owner.Name; //所有者
        //         cpa.invcode = cp.Product__r.NCCode__c; //产品的NCCode__c
        //         cpa.noriginalcurtaxprice = String.valueof(cp.SalesPrice__c)  ; //SalesPrice__c
        //         cpa.nitemdiscountrate = '0';//默认0
        //         cpa.nnumber = String.valueof(cp.Number__c);
        //         cpa.opertype = t; //操作类型   1=新增  2=修改  3=删除
        //         cpa.quotetype = qt; //报价类型   1=报价  2=调价
        // cpa.csalequotationid = id;
        //         cpa.csalequotation_bid = cp.Id;
        //         cpa.adjustid = id;
        //         cpa.adjust_pid = cp.Id; 
        //         cpa.addCustomer =cp.Contract__r.TerminalCustomer__r.NCICCode__c;
        //         conProductArgsList.add(cpa);
        //       }             
        //     }

        
            
              //Map<String ,List<ConProductArgs>>data = new Map<String ,List<ConProductArgs>>();
            // data.put('data',conProductArgsList);

             String msg = sycToNc(conProductArgsList); 

             if(msg == 'OK'){
                for (ContractProduct__c cp : cpList) {
                  cp.IsSycToNc__c = true;
                }
                if(cpList.size() > 0)update cpList;

             }
             return msg;


         
    }

     WebService static String postMeasureProduct(String mainId){

        Measure_Calculate__c mp = [select Id,WhetherSynchronizeNC__c,WhetherReverse__c ,CreatedBy.Name,Opportunity__r.Account.AccountNumber,CreatedDate,
        Opportunity__r.ExecutiveCompany__r.AccountNumber,Opportunity__r.ExecutiveCompany__r.RecordType.DeveloperName,Opportunity__r.Owner.Manager.Name,Opportunity__r.Owner.Name,Company__c from Measure_Calculate__c where Id=:mainId];
        if(mp.WhetherReverse__c == true && mp.WhetherSynchronizeNC__c == true) return '请勿重复点击同步!';

        List<Measure_Calculate_Product__c> mcpList = [select Id,Product__r.NCCode__c,Product__r.Name ,SalesPriceWT__c ,DealerInstCost__c from Measure_Calculate_Product__c where Measure_Calculate__c =:mainId and IsEquipRelated__c = false];
        if(mcpList.size() == 0)return 'NO DATA';

        String accountNumber = mp.Opportunity__r.ExecutiveCompany__r.RecordType.DeveloperName == 'Maccura' ? mp.Opportunity__r.Account.AccountNumber : mp.Opportunity__r.ExecutiveCompany__r.AccountNumber ; 
         Map<String,String>comMap =  ImportObject.getPicklistValues('Contract__c', 'Corpcode__c', false);
        String salescode  = ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false).get(mp.Company__c);

        List<ConProductArgs> mList = new List<ConProductArgs>();
        //Datetime d  = Datetime.valueOf('2019-04-08 13:32:00');
        for (Measure_Calculate_Product__c mcp : mcpList) {
            ConProductArgs cpa = new ConProductArgs();
                cpa.corpcode = comMap.get(mp.Company__c);  //公司编码
                cpa.custcode = accountNumber;  //客户编码
                cpa.vsalestrucode = salescode ; //销售组织编码
                cpa.created_by =mp.Opportunity__r.Owner.Name ; //创建人名字
                cpa.sub_corp_manager = mp.Opportunity__r.Owner.Manager.Name;  //报价的销售中心总监名字
                //cpa.csourcecode = cp.Contract__r.ContractNumber__c; //合同自动编号
                cpa.ts = Utils.date2string(System.now()) ; //合同的lastmodifieddate
                cpa.cemployeecode = mp.Opportunity__r.Owner.Name; //所有者
                cpa.invcode = mcp.Product__r.NCCode__c; //产品的NCCode__c
                cpa.dreceiptdate  = Utils.date2string(Date.valueOf(System.now()));//报价日期
                if(mcp.SalesPriceWT__c == null)return mcp.Product__r.Name  + '没有价格,不能同步!';

                  cpa.noriginalcurtaxprice = String.valueof(mcp.SalesPriceWT__c) ;

                

               
               //SalesPrice__c
                cpa.nitemdiscountrate = '100';//默认100
                //cpa.nnumber = String.valueof(cp.Number__c);
                cpa.opertype = '1'; //操作类型   1=新增  2=修改  3=删除
                cpa.quotetype = '1'; //报价类型   1=报价  2=调价
                cpa.csalequotationid = mainId;
                cpa.csalequotation_bid = mcp.Id;
                cpa.currtypename = '人民币';

               // cpa.addCustomer =cp.Contract__r.TerminalCustomer__r.NCICCode__c;
                mList.add(cpa);

        }

        String msg = '';

            if(mp.WhetherSynchronizeNC__c == true || (mp.Opportunity__r.Account.AccountNumber != null && mp.Opportunity__r.Account.AccountNumber.contains('DSF'))) {
               msg = 'OK';
            }else{

               
                msg = sycToNc(mList);

                  
              
            }
            if(msg == 'OK'){
               mp.WhetherSynchronizeNC__c = true;
                update mp;
              String res ='';
                if(mp.WhetherReverse__c == false){
                  res = AdjustPriceHandler.adjustMeasuerToPriceList(mainId);
                }else{
                  return '同步并反写成功!';
                }
               
                if(res == 'OK')return 'OK';

                return '同步成功!'+res;
              
            }else{
              return msg;
            }

          

        //return  sycToNc(mList);
     }



     WebService static String postQuoteProduct(String mainId){
        Quote q =[select CreatedBy.Name,Id,Opportunity.Account.AccountNumber,Opportunity.RecordType.DeveloperName , Opportunity.ExecutiveCompany__r.AccountNumber,Opportunity.ExecutiveCompany__r.RecordType.DeveloperName,WhetherSynchronizeNC__c ,WhetherReverse__c,Type__c,
        Opportunity.Owner.SubCompany__c,Opportunity.Owner.Name,Opportunity.Owner.Manager.Name from Quote where Id=:mainId];

        if(q.WhetherReverse__c == true && q.WhetherSynchronizeNC__c == true) return '请勿重复点击同步!';
        if(q.Type__c == '仪器报价')return '仪器报价不能反写到价目表!';

        String accountNumber = q.Opportunity.ExecutiveCompany__r.RecordType.DeveloperName == 'Maccura' ? q.Opportunity.Account.AccountNumber : q.Opportunity.ExecutiveCompany__r.AccountNumber ; 
        if(q.Opportunity.RecordType.DeveloperName == 'DealerOpportunity'||q.Opportunity.RecordType.DeveloperName == 'OverseaDearlerOpportunity')accountNumber = q.Opportunity.Account.AccountNumber;

        Map<String,String>comMap =  ImportObject.getPicklistValues('Contract__c', 'Corpcode__c', false);
        String salescode  = ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false).get(q.Opportunity.Owner.SubCompany__c);
        List<QuoteProduct__c> qList = [select Id,Product__c ,Product__r.Name,SalesPrice__c ,Product__r.NCCode__c from QuoteProduct__c where Quote__c =:q.Id];
        if(qList.size() == 0)return 'NO DATA';
          List<ConProductArgs> productArgsList = new List<ConProductArgs>();

          for (QuoteProduct__c qp : qList) {

                ConProductArgs cpa = new ConProductArgs();

                cpa.corpcode = comMap.get(q.Opportunity.Owner.SubCompany__c);  //公司编码
                cpa.custcode = accountNumber;  //客户编码
                cpa.vsalestrucode = salescode ; //销售组织编码
                cpa.created_by = q.Opportunity.Owner.Name; //创建人名字
                cpa.sub_corp_manager = q.Opportunity.Owner.Manager.Name;  //报价的销售中心总监名字
                //cpa.csourcecode = cp.Contract__r.ContractNumber__c; //合同自动编号
                cpa.ts = Utils.date2string(System.now()) ; //合同的lastmodifieddate
                cpa.cemployeecode = q.Opportunity.Owner.Name; //所有者
                cpa.invcode = qp.Product__r.NCCode__c; //产品的NCCode__c\
                cpa.dreceiptdate  = Utils.date2string(Date.valueOf(System.now()));//报价日期
                
                if(qp.SalesPrice__c == null)return qp.Product__r.Name  + '没有价格,不能同步!';
                 cpa.noriginalcurtaxprice = String.valueof(qp.SalesPrice__c); 
                
               //SalesPrice__c
                cpa.nitemdiscountrate = '100';//默认100
                //cpa.nnumber = String.valueof(cp.Number__c);
                cpa.opertype = '1'; //操作类型   1=新增  2=修改  3=删除
                cpa.quotetype = '1'; //报价类型   1=报价  2=调价
                cpa.csalequotationid = mainId;
                cpa.csalequotation_bid = qp.Id;
                cpa.currtypename = '人民币';
               // cpa.addCustomer =cp.Contract__r.TerminalCustomer__r.NCICCode__c;
                productArgsList.add(cpa);
              
          }

           String msg = '';

            if(q.WhetherSynchronizeNC__c == true || (q.Opportunity.Account.AccountNumber != null && q.Opportunity.Account.AccountNumber.contains('DSF'))) {
               msg = 'OK';
            }else{

               
                msg = sycToNc(productArgsList);
                  
              
            }
            if(msg == 'OK'){
               q.WhetherSynchronizeNC__c = true;
                update q;
              String res ='';
                if(q.WhetherReverse__c == false){
                  res = AdjustPriceHandler.adjustQuoteToPriceList(mainId);
                }else{
                  return '同步并反写成功!';
                }
               
                if(res == 'OK')return 'OK';

                return '同步成功!'+res;
              
            }else{
              return msg;
            }



     }

*/  


     //获取价目表
    public static List<Object>  getJmcode(String corp ){

      String url = Label.queryResposityURL;

      String sql = ' select cpricetariffcode jmcode, cpricetariffname jmname ,b.unitcode corpcode  from prm_tariff  a left join bd_corp b on a.pk_corp = b.pk_corp where  b.unitcode =\''+corp+'\' ' ;
        sql = '{"data":" '+ sql+'"}';
        System.debug(sql);
        //请求
        HttpRequest req = new HttpRequest();
        req.setBody(sql);
        req.setMethod('POST');
        req.setHeader('Content-Type','text/plain');
        req.setEndpoint(url);
        HttpResponse res = Utils.postRequest(req, 2);
      ///返回结果处理
        if (res.getStatusCode() == 200) {
            System.debug(res.getBody());
            Map<String,Object> r = null;
              //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{\"result_msg\":\"查询成功！\",\"result\":1,\"data\":[{\"nccode\":\"111\",\"company\":\"111\",\"djh\":\"111\",\"djdate\":\"111\",\"signdate\":\"111\",\"termaccount\":\"111\",\"payaccount\":\"111\",\"xydqr\":\"111\",\"ye\":\"111\",\"psncode\":\"111\",\"psnname\":\"111\",\"prodlinecode\":\"111\",\"prodlinename\":\"111\",\"djrq\":\"111\",\"djbh\":\"111\",\"currtypename\":\"111\"}]}');
                    r =  resBody;

                }else{

                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());

                }
          if(r.get('code') == 0 || r.get('code') == '0'){
              Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
                if( rs.get('result') == 1 ){

                   return (List<Object>) rs.get('data');

               }else{

                  throw new DmlException(String.valueOf(rs.get('result_msg')));

               }

        }else{
           throw new DmlException('获取价目表信息失败 : '+String.valueOf(r.get('msg')));
        }

      }else{
         throw new DmlException('获取价目表信息失败 : '+res.getBody());
      }
    }

     //同步价格分组

     WebService static String postAdGroupPrice(String mainId ){
        AdjustPrice__c ap =[select OwnerId,Id,Name,Account__r.PriceGroup__c,EffectiveDateFrom__c,SalesCode__c,Result__c,Account__r.Name,Account__r.AccountNumber,WhetherSynchronizeNC__c ,WhetherReverse__c from AdjustPrice__c where Id=:mainId];

        try {

            if(ap.WhetherReverse__c == true && ap.WhetherSynchronizeNC__c == true) return '请勿重复点击同步!';
            if(ap.WhetherSynchronizeNC__c !=true  ){
            if(String.isBlank(ap.Account__r.PriceGroup__c))throw new DmlException('请维护客户的价格分组');

                List<AdjustPriceProduct__c> apList = [select Id,Product__r.Name  ,Product__r.NCCode__c,AdjustPrice__r.Account__r.AccountNumber,
                AdjustPrice__r.SalesCode__c,OriginalPrice__c,AdjustSalesPrice__c,
                AdjustPrice__r.OwnerId,AdjustPrice__r.Owner.Name ,AdjustPrice__r.CreatedBy.Name ,AdjustPrice__r.Company__c
                  from AdjustPriceProduct__c where AdjustPrice__c =:mainId ];

                User u = [select Id,Name,Manager.Name  from User where  Id=:ap.OwnerId];
                List<ProductBean> pList = new List<ProductBean>();
                Map<String,String>comMap =  ImportObject.getPicklistValues('Contract__c', 'Corpcode__c', false);
                Map<String,String>sMap  =  ImportObject.getPicklistValues('AdjustPrice__c', 'SalesCode__c', true);
                String corp = comMap.get( sMap.get(ap.SalesCode__c)); 
                ///获取价目表信息
                List<Object> jcodes = getJmcode(corp);

                if(jcodes == null || jcodes.isEmpty()) throw new DmlException('没有获取到:'+corp+'NC价目表信息');
                Map<String,Object> dataMap = ( Map<String,Object>)jcodes.get(0);
                for( AdjustPriceProduct__c bg : apList){

                    ProductBean pb = new ProductBean();
                    pb.tjdate = System.now().format('yyyy-MM-dd');
                    pb.jmcode = String.valueOf(dataMap.get('jmcode'));
                   // pb.jmname = String.valueOf(dataMap.get('jmname'));
                    pb.ccustclass = ap.Account__r.PriceGroup__c;
                  //  checkNull(pb.jmcode,String.valueOf(dataMap.get('jmname'))  +'不存在!');
                    pb.corpcode = String.valueOf(dataMap.get('corpcode'));
                  //  checkNull(pb.corpcode,String.valueOf(dataMap.get('jmname'))  +'不存在!');
                    pb.dreceiptdate = System.now().format('yyyy-MM-dd');
                    pb.dexpiredate = System.now().addMonths(1).format('yyyy-MM-dd');
                    pb.cadjpriceid = ap.Id ;
                    pb.cadjprice_bid = bg.Id ; 
                    pb.invcode = bg.Product__r.NCCode__c;
                    if(String.isBlank(pb.invcode)) throw new DmlException(bg.Product__r.Name  +'不存在产品编码!');
                    pb.custcode = ap.Account__r.AccountNumber;
                    if(String.isBlank(pb.custcode)) throw new DmlException('未维护客户编码!');
                    pb.fadjtype = 0;
                    pb.jgtype = '成交价';
                    pb.newprice = String.valueOf(bg.AdjustSalesPrice__c);
                    //dtstoptime;//失效时间止dvalidate;//有效日期起dtstarttime;//有效时间起
                    pb.dtstoptime =  System.now().format('HH:mm:ss');
                    pb.dvalidate = System.now().format('yyyy-MM-dd');//
                    pb.dtstarttime = System.now().format('HH:mm:ss');

                    pb.baseprice = '0'; 
                    pb.jgzs = '1';
                    pb.jgjc = '0';
                    pb.ts = System.now().format('yyyy-MM-dd HH:mm:ss');
                    pb.created_by = u.Name;
                    pb.sub_corp_manager = u.Manager.Name;
                    pb.vmemo= ap.Name;
                    pList.add(pb);
                 }

                  
                

                  String result =  syncTjd(pList);
                  result = ap.Result__c  == null ? result : ap.Result__c +result;
                  if(result.length() > 255) result = result.substring(0, 254);
                  ap.Result__c = result;
                  ap.WhetherSynchronizeNC__c = true;
                  update ap;
            }
        }catch (Exception e) {
            return e.getMessage();
        }

         if(ap.WhetherReverse__c == false){
            return AdjustPriceHandler.adjustPriceToPriceList(mainId);
          }else{
            return '同步并反写成功!';
          }
        

          
     }

     public static String syncTjd(List<ProductBean> pList ){
          Map<String ,List<ProductBean>>temp = new Map<String ,List<ProductBean>>();
          temp.put('data',pList);

          String body = JSON.serialize(temp);
          System.debug(body);
          HttpRequest req = new HttpRequest();
          req.setBody(body);
          //return body;
          req.setMethod('POST');
          req.setHeader('Content-Type','text/plain');
          // 接口写在自定义标签的quoteUrl里面
          //System.Label.quoteUrl
          //调价单
          String url = Label.QueryTjdPutUrl;
          req.setEndpoint(url);

          System.debug('+++'+ body);
          
          HttpResponse res = Utils.postRequest(req, 1);
           System.debug('+++'+res.getBody());
       
          if (res.getStatusCode() == 200) {
              Map<String,Object> r = new Map<String,Object>();
              //如果是测试
              if(Test.isRunningTest()){

                  Map<String,Object>  resBody= new Map<String,Object>();
                resBody.put('code','0');
                resBody.put('result','{\"result_msg\":\"操作成功！\",\"result\":1,\"data\":{\"ts\":\"2018-01-04 16:24:18\"}}');
                  r =  resBody;
              }else{
                   r  = (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
 
              }
             // return res.getBody();
               if(r.get('code') == 0 || r.get('code') == '0'){
                  Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
              
               
                 if (rs.get('result') == 1 ) {
          
                      return res.getBody(); 
                     
                 }else{

                    throw new DmlException('同步失败:' +(String) rs.get('result_msg')  );
                 }
                   
               }else{
                 throw new DmlException('系统提示:' + (String)r.get('msg')) ;
               }
    

          } else {
              throw new DmlException('系统错误:'+res.toString()+',请联系系统管理员!');
          }

         


     }


     public class ProductBean{
      public String tjdate;//调价日期
      public String jmcode;//价目表编码
      //public String jmname;//价目表名称
      public String corpcode; //公司编码 
      //public String corpname; //公司名称

      public String dreceiptdate; //有效期从
      public String dexpiredate; //有效期至
      public String cadjpriceid; //调价单主表pk
      public String cadjprice_bid; //调价单子表pk 

      public String invcode; //产品编码
      public String custcode;//客户编码
      public String jgtype;//价格项
      public String newprice; //新建价格
      public String baseprice; //基价
      public Integer fadjtype ;//调价单类型-- 1:[调促销策略]-- 0:[调基价]-- 2:[调基准折扣]
            //dtstoptime;//失效时间止dvalidate;//有效日期起dtstarttime;//有效时间起
      public String dtstoptime ;//失效时间止
      public String dvalidate; //有效日期起
      public String dtstarttime;  //有效时间起

      public String jgzs; //价格指数 
      public String jgjc ; //价格加成
      public String ts; 

      public String created_by;//制单人
      public String sub_corp_manager;//审核人

      public String vmemo;//备注

      public String ccustclass;//客户价格分组;



    }
    //同步报价单 
     WebService  static String postAdprice(String mainId ){


        try {

          AdjustPrice__c ap =[select Id,EffectiveDateFrom__c,Result__c,Account__r.Name,Account__r.AccountNumber,WhetherSynchronizeNC__c ,WhetherReverse__c from AdjustPrice__c where Id=:mainId];

          if(ap.WhetherReverse__c == true && ap.WhetherSynchronizeNC__c == true) return '请勿重复点击同步!';
          List<AdjustPriceProduct__c> apList = [select Id,Product__r.Name  ,Product__r.NCCode__c,AdjustPrice__r.Account__r.AccountNumber,
          AdjustPrice__r.SalesCode__c,OriginalPrice__c,AdjustSalesPrice__c,
          AdjustPrice__r.OwnerId,AdjustPrice__r.Owner.Name ,AdjustPrice__r.CreatedBy.Name ,AdjustPrice__r.Company__c
            from AdjustPriceProduct__c where AdjustPrice__c =:mainId ];

            if(apList.size() == 0)return '没有可同步的数据!';
             AdjustPriceProduct__c ap1  = apList[0];
              User u = [select Id, Manager.Name from User where Id =:ap1.AdjustPrice__r.OwnerId];
              List<ConProductArgs> conProductArgsList = new List<ConProductArgs>();
              Map<String,String>comMap =  ImportObject.getPicklistValues('Contract__c', 'Corpcode__c', false);
              Map<String,String>sMap  =  ImportObject.getPicklistValues('AdjustPrice__c', 'SalesCode__c', true);
              for (AdjustPriceProduct__c app: apList) {
                  ConProductArgs cpa = new ConProductArgs();
                  cpa.corpcode = comMap.get( sMap.get(app.AdjustPrice__r.SalesCode__c));  //公司编码
                  cpa.custcode = app.AdjustPrice__r.Account__r.AccountNumber;  //客户编码
                  cpa.vsalestrucode = app.AdjustPrice__r.SalesCode__c ; //销售组织编码
                  cpa.created_by = app.AdjustPrice__r.Owner.Name; //创建人名字
                  cpa.sub_corp_manager = u.Manager.Name;  //报价的销售中心总监名字
                  //cpa.csourcecode = cp.Contract__r.ContractNumber__c; //合同自动编号
                  cpa.ts = Utils.date2string(System.now()) ; //合同的lastmodifieddate
                  cpa.cemployeecode = app.AdjustPrice__r.Owner.Name; //所有者
                  cpa.invcode = app.Product__r.NCCode__c; //产品的NCCode__c
                  cpa.dreceiptdate  = Utils.date2string(Date.valueOf(System.now()));//报价日期
                  if(app.AdjustSalesPrice__c == null)return app.Product__r.Name  + '没有价格,不能同步!';
                   cpa.noriginalcurtaxprice = String.valueof(app.AdjustSalesPrice__c); 
                  
                 //SalesPrice__c
                  cpa.nitemdiscountrate = '100';//默认100
                  //cpa.nnumber = String.valueof(cp.Number__c);
                  cpa.opertype = '1'; //操作类型   1=新增  2=修改  3=删除
                  cpa.quotetype = '1'; //报价类型   1=报价  2=调价
                  cpa.csalequotationid = mainId;
                  cpa.csalequotation_bid = app.Id;
                  cpa.currtypename = '人民币';
                  cpa.dvalidate =  ap.EffectiveDateFrom__c != null ? Utils.date2string( ap.EffectiveDateFrom__c) : '';
                 // cpa.addCustomer =cp.Contract__r.TerminalCustomer__r.NCICCode__c;
                  conProductArgsList.add(cpa);
                  
              }
              if(conProductArgsList.isEmpty()) return '没有可同步的数据!';
              String msg = '';
               System.debug('PriceListControllerTest==>postAdprice');

              // if(ap.WhetherSynchronizeNC__c == true || (ap.Account__r.AccountNumber != null && ap.Account__r.AccountNumber.contains('DSF'))) {
              //    msg = 'OK';
              // }else{
              //   msg = sycToNcNew(conProductArgsList);
                
              // }
              if(ap.WhetherSynchronizeNC__c != true &&  !ap.Account__r.Name.contains('报价/调价专用')){

                  String result =  sycToNcNew(conProductArgsList);
                  result = ap.Result__c  == null ? result : ap.Result__c +result;
                  if(result.length() > 255) result = result.substring(0, 254);
                  ap.Result__c = result;
                  ap.WhetherSynchronizeNC__c = true;
                  update ap;
                  
              }
              String res ='';
              if(ap.WhetherReverse__c == false){
                return AdjustPriceHandler.adjustPriceToPriceList(mainId);
              }else{
                return '同步并反写成功!';
              }
            
        }catch (Exception  e) {
            return '同步失败:'+e.getMessage();
        }
        
         
          

     }

     /*

     WebService  static String postOverseaAdprice(String mainId ){
        AdjustPrice__c ap =[select Id,Account__r.AccountNumber,WhetherRegentReverse__c,WhetherRegentSynchronizeNC__c, WhetherSynchronizeNC__c ,WhetherReverse__c from AdjustPrice__c where Id=:mainId];
        //isEquip &&
        if( ap.WhetherReverse__c == true && ap.WhetherSynchronizeNC__c == true) return '请勿重复点击同步!';
        //if( !isEquip && ap.WhetherRegentReverse__c == true && ap.WhetherRegentSynchronizeNC__c == true) return '请勿重复点击同步!';
        
        String sql = 'select Id,Product__r.Name ,PresentPrice__c,Product__r.Category3__c ,Product__r.RelatedProducts__c,Product__r.NCCode__c,AdjustPrice__r.Account__r.AccountNumber,'+
        ' AdjustPrice__r.SalesCode__c,OriginalPrice__c,AdjustSalesPrice__c,'+
        ' AdjustPrice__r.OwnerId,AdjustPrice__r.Owner.Name ,AdjustPrice__r.CreatedBy.Name ,AdjustPrice__r.Company__c '+
        ' from AdjustPriceProduct__c where AdjustPrice__c =\''+mainId+'\'   ';
       // if(isEquip) sql += ' and Product__r.Category3__c not in ' + Label.RegentCatagory3;
       // if(!isEquip) sql += ' and Product__r.Category3__c in ' + Label.RegentCatagory3;

        List<AdjustPriceProduct__c> apList = Database.query(sql);

          if(apList.size() == 0)return 'NO DATA';


           AdjustPriceProduct__c ap1  = apList[0];

            User u = [select Id, Manager.Name from User where Id =:ap1.AdjustPrice__r.OwnerId];

        Map <String,String> salescodeMap =  ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false);
        String swsalescode = salescodeMap.get('迈克生物股份有限公司');
       // String dzsalescode = salescodeMap.get('迈克医疗电子有限公司');

            List<ConProductArgs> conProductArgsList = new List<ConProductArgs>();

            Map<String,ConProductArgs> productMap  =new Map<String,ConProductArgs>();
            //<code1 ,code2>
            Map<String,String> nccodeMap = new Map<String,String>();

            for (AdjustPriceProduct__c app: apList) {
                if(app.Product__r.Category3__c == null) return app.Product__r.Name +'三级分类为空!请维护!';
                ConProductArgs cpa = new ConProductArgs();
                cpa.corpcode =  'MKSW';//isEquip ? 'MKDZ': 'MKSW' ;  //公司编码
                cpa.custcode = app.AdjustPrice__r.Account__r.AccountNumber;  //客户编码
                cpa.vsalestrucode = swsalescode;//isEquip ? dzsalescode: swsalescode; //销售组织编码
                cpa.created_by = app.AdjustPrice__r.Owner.Name; //创建人名字
                cpa.sub_corp_manager = u.Manager.Name;  //报价的销售中心总监名字
                //cpa.csourcecode = cp.Contract__r.ContractNumber__c; //合同自动编号
                cpa.ts = Utils.date2string(System.now()) ; //合同的lastmodifieddate
                cpa.cemployeecode = app.AdjustPrice__r.Owner.Name; //所有者
                cpa.invcode = app.Product__r.NCCode__c; //产品的NCCode__c
                cpa.dreceiptdate  = Utils.date2string(Date.valueOf(System.now()));//报价日期
                if(app.PresentPrice__c  == null)return app.Product__r.Name  + '没有价格,不能同步!';

                 cpa.noriginalcurtaxprice = String.valueof(app.PresentPrice__c); 
                 cpa.currtypename = '美元';
               //SalesPrice__c
                cpa.nitemdiscountrate = '100';//默认100
                //cpa.nnumber = String.valueof(cp.Number__c);
                cpa.opertype = '1'; //操作类型   1=新增  2=修改  3=删除
                cpa.quotetype = '1'; //报价类型   1=报价  2=调价
                cpa.csalequotationid = mainId;
                cpa.csalequotation_bid = app.Id;
               // cpa.addCustomer =cp.Contract__r.TerminalCustomer__r.NCICCode__c;
                conProductArgsList.add(cpa);
                productMap.put(cpa.invcode, cpa);
                

                if(app.Product__r.RelatedProducts__c != null){

                    for(String code : app.Product__r.RelatedProducts__c.split('\\*')){

                        if(code != cpa.invcode){
                           nccodeMap.put(code,cpa.invcode);
                        }
                    }
                }
                
            }
            Integer i = 1;
            for(String code : nccodeMap.keySet()){

                if(productMap.containsKey(code))continue;
                ConProductArgs crgs = productMap.get(nccodeMap.get(code));
                ConProductArgs crgs1 = crgs.clone();

                crgs1.invcode = code;
                crgs1.csalequotation_bid = i+'-' +crgs1.csalequotation_bid;
                conProductArgsList.add(crgs1);
                i++;

            }

            String msg = '';
             System.debug('QuoteAboardControllerTest==>postOverseaAdprice');
             msg = ap.WhetherSynchronizeNC__c == true ? 'OK' : sycToNc(conProductArgsList);

          
            if(msg == 'OK'){
                ap.WhetherSynchronizeNC__c = true;
               //if(!isEquip )ap.WhetherRegentSynchronizeNC__c = true;
                update ap;
                String res = ap.WhetherReverse__c == false ? AdjustPriceHandler.adjustAboardPriceToPriceList(mainId ) : '同步并反写成功!';
               
               
                //if(res == 'OK')return 'OK';

                return res;
              
            }else{
              return msg;
            }


     }
     */


     /*
    id 合同id 
    t 操作类型   1=新增  2=修改  3=删除 
    qt 报价类型   1=报价  2=调价
    */
    ///2018-01-02 全部同步为报价单
    // 调用NC接口
    /*
    WebService static String postToNC(Id id) {
        

            Contract__c con = [select Id,NCTime__c from Contract__c where Id=:id];

            List<ContractReagentInformation__c> cpList = [select Contract__r.OwnerId,
                                               Contract__r.Corpcode__c, Contract__r.Account__r.AccountNumber, CreatedBy.Name,
                                                Contract__r.ContractNumber__c, Contract__r.LastModifiedDate, Contract__r.Owner.Name,
                                                ReagentProducts__r.NCCode__c, Price__c,Contract__r.TerminalCustomer__r.NCICCode__c from ContractReagentInformation__c
                                                where Contract__c = :id and NC__c = false ];
            if (cpList.size() == 0) {
                return '没有未同步的试剂';
            }


            ContractReagentInformation__c cp1  = cpList[0];
             User u = [select Id, Manager.Name from User where Id =:cp1.Contract__r.OwnerId];

            Map<String,String> salesMap = ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false);
            Map<String,String > companyMap = ImportObject.getPicklistValues('Contract__c', 'CorpCode__c', true);

            
            ///后期处理数据不正常的问题
            List<ConProductArgs> conProductArgsList = new List<ConProductArgs>();
            
              for (ContractReagentInformation__c cp : cpList) {
                ConProductArgs cpa = new ConProductArgs();

                cpa.corpcode = cp.Contract__r.Corpcode__c;  //公司编码
                cpa.custcode = cp.Contract__r.Account__r.AccountNumber ;  //客户编码

                cpa.vsalestrucode =salesMap.get(companyMap.get(cp.Contract__r.Corpcode__c));//cp.Contract__r.Vsalestrucode__c ; //销售组织编码

                if( cpa.vsalestrucode == null ) return '请维护公司信息!';

                cpa.created_by = cp.Contract__r.Owner.Name; //创建人名字
                cpa.sub_corp_manager = u.Manager.Name;  //报价的销售中心总监名字
                cpa.csourcecode = cp.Contract__r.ContractNumber__c; //合同自动编号
                cpa.ts = Utils.date2string(System.now()) ; //合同的lastmodifieddate
                cpa.cemployeecode = cp.Contract__r.Owner.Name; //所有者
                cpa.invcode = cp.ReagentProducts__r.NCCode__c; //产品的NCCode__c
                cpa.dreceiptdate  = Utils.date2string(Date.valueOf(System.now()));//报价日期
                cpa.noriginalcurtaxprice = String.valueof(cp.Price__c)  ; //SalesPrice__c
                cpa.nitemdiscountrate = '100';//默认100
              //  cpa.nnumber = String.valueof(cp.Number__c);
                cpa.opertype = '1';//'t; //操作类型   1=新增  2=修改  3=删除
                cpa.quotetype = '1'; //报价类型   1=报价  2=调价
                cpa.csalequotationid = id;
                cpa.csalequotation_bid = cp.Id;
                cpa.currtypename = '人民币';
               if(cp.Contract__r.TerminalCustomer__r.NCICCode__c != null ) cpa.addCustomer =cp.Contract__r.TerminalCustomer__r.NCICCode__c;

               
                conProductArgsList.add(cpa);
              }

             String msg = sycToNc(conProductArgsList); 
             System.debug('QuoteAboardControllerTest==>postToNC');
             if(msg == 'OK'){
                for (ContractReagentInformation__c cp : cpList) {
                  cp.NC__c = true;
                }
             

                 if(cpList.size() > 0)update cpList;
                 con.NCTime__c = System.now();

                 update con;
                 

                 msg = AdjustPriceHandler.adjustContract(con.Id );
                 if(msg == 'OK'){

                    msg = '同步并反写到价目表成功!';

                 }else{
                    msg = '同步成功!但反写到价目表失败:'+msg;
                 }
            
               
             }
             return msg;


         
    }
    */

     /*
    id 合同id 
    t 操作类型   1=新增  2=修改  3=删除 
    qt 报价类型   1=报价  2=调价
    */
    ///2018-01-02 全部同步为报价单
    // 调用NC接口
    WebService static String postOppToNC(Id id) {
        
        try {
            Opportunity opp = [select Id,NCResult__c from Opportunity where Id=:id];

            List<ContractReagentInformation__c> cpList = [select Opportunity__r.OwnerId,

                                               Opportunity__r.Corpcode__c, Opportunity__r.Account.AccountNumber, CreatedBy.Name,
                                                Opportunity__r.LastModifiedDate, Opportunity__r.Owner.Name,Opportunity__r.OppNo__c,
                                                ReagentProducts__r.NCCode__c, Price__c,Opportunity__r.TerminalCustomer__r.NCICCode__c from ContractReagentInformation__c
                                                where Opportunity__c = :id and NC__c = false ];
         

            ContractReagentInformation__c cp1  = cpList[0];
             User u = [select Id, Manager.Name from User where Id =:cp1.Opportunity__r.OwnerId];

            Map<String,String> salesMap = ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false);
            Map<String,String > companyMap = ImportObject.getPicklistValues('Opportunity', 'CorpCode__c', true);

            
            ///后期处理数据不正常的问题
            List<ConProductArgs> conProductArgsList = new List<ConProductArgs>();
            
              for (ContractReagentInformation__c cp : cpList) {
                ConProductArgs cpa = new ConProductArgs();
                
                cpa.corpcode = cp.Opportunity__r.Corpcode__c;  //公司编码
                cpa.custcode = cp.Opportunity__r.Account.AccountNumber ;  //客户编码

                cpa.vsalestrucode =salesMap.get(companyMap.get(cp.Opportunity__r.Corpcode__c));//cp.Contract__r.Vsalestrucode__c ; //销售组织编码

                if( cpa.vsalestrucode == null ) return '请维护公司信息!';

                cpa.created_by = cp.Opportunity__r.Owner.Name; //创建人名字
                cpa.sub_corp_manager = u.Manager.Name;  //报价的销售中心总监名字
                cpa.csourcecode = cp.Opportunity__r.OppNo__c; //合同自动编号
                cpa.ts = Utils.date2string(System.now()) ; //合同的lastmodifieddate
                cpa.cemployeecode = cp.Opportunity__r.Owner.Name; //所有者
                cpa.invcode = cp.ReagentProducts__r.NCCode__c; //产品的NCCode__c
                cpa.dreceiptdate  = Utils.date2string(Date.valueOf(System.now()));//报价日期
                cpa.noriginalcurtaxprice = String.valueof(cp.Price__c)  ; //SalesPrice__c
                cpa.nitemdiscountrate = '100';//默认100
              //  cpa.nnumber = String.valueof(cp.Number__c);
                cpa.opertype = '1';//'t; //操作类型   1=新增  2=修改  3=删除
                cpa.quotetype = '1'; //报价类型   1=报价  2=调价
                cpa.csalequotationid = id;
                cpa.csalequotation_bid = cp.Id;
                cpa.currtypename = '人民币';
               if(cp.Opportunity__r.TerminalCustomer__r.NCICCode__c != null ) cpa.addCustomer =cp.Opportunity__r.TerminalCustomer__r.NCICCode__c;

               
                conProductArgsList.add(cpa);
              }
              if(!conProductArgsList.isEmpty() ) {

                  String result = sycToNcNew(conProductArgsList); 
                  if(opp.NCResult__c != null )result= opp.NCResult__c +result;
                  if(result != null && result.length() > 255 )result = result.substring(0, 254);

                  System.debug('QuoteAboardControllerTest==>postToNC');
                    opp.NCResult__c = result;

                  for (ContractReagentInformation__c cp : cpList) {
                       cp.NC__c = true;
                   }
                    update opp;
                    if(cpList.size() > 0)update cpList;

                  
              }
              
                try {
                   AdjustPriceHandler.adjustOpp(opp.Id );
                }catch (Exception e) {
                    
                    return '同步NC成功!'+e.getMessage();
                }

                return '同步NC成功!';
                                       
        }catch (Exception e) {
            return '同步失败:'+e.getMessage();
        }
        
        
         
    }

    /*
     WebService static String  postOverseaQuote(String mainId ){

        Quote q =[select CreatedBy.Name,Id,Opportunity.Account.AccountNumber,WhetherSynchronizeNC__c ,WhetherRegentSynchronizeNC__c,WhetherRegentReverse__c,WhetherReverse__c,
        Opportunity.Owner.SubCompany__c,Opportunity.Owner.Name,Opportunity.Owner.Manager.Name from Quote where Id=:mainId];
        if( q.WhetherReverse__c == true && q.WhetherSynchronizeNC__c == true) return '请勿重复点击同步!';


        //if( isEquip && q.WhetherReverse__c == true && q.WhetherSynchronizeNC__c == true) return '请勿重复点击同步!';
        //if( !isEquip && q.WhetherRegentReverse__c == true && q.WhetherRegentSynchronizeNC__c == true) return '请勿重复点击同步!';

        String accountNumber = q.Opportunity.Account.AccountNumber;


        Map <String,String> salescodeMap =  ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false);
        String swsalescode = salescodeMap.get('迈克生物股份有限公司');
       // String dzsalescode = salescodeMap.get('迈克医疗电子有限公司');

       // dzsalescode = '01';
        String corp =  'MKSW';//isEquip ? 'MKDZ': 'MKSW';
        //corp = 'MKSW';
        String sql = 'select Id,Product__c,Product__r.RelatedProducts__c  ,CooperativePrice__c,Product__r.Category0__c,Product__r.Name,Product__r.Category3__c ,Product__r.NCCode__c from QuoteProduct__c where Quote__c =\''+mainId+'\' ';
       // if(isEquip) sql += ' and Product__r.Category3__c not in ' + Label.RegentCatagory3;
       // if(!isEquip) sql += ' and Product__r.Category3__c in ' + Label.RegentCatagory3;


        List<QuoteProduct__c> qList = Database.query(sql);
        if(qList.size() == 0)return 'NO DATA';
          Map<String,ConProductArgs>productMap =new Map<String,ConProductArgs>();
          Map<String,String> nccodeMap = new Map<String,String>();
         // List<ConProductArgs> equipArgsList = new List<ConProductArgs>();
          List<ConProductArgs> productArgsList = new List<ConProductArgs>();
          for (QuoteProduct__c qp : qList) {

                if(qp.Product__r.Category3__c == null) return qp.Product__r.Name +'三级分类为空!请维护!';

                ConProductArgs cpa = new ConProductArgs();
                //Boolean isEquip =eSet.contains(qp.Product__r.Category0__c) ;
                cpa.corpcode = corp;  //公司编码
                cpa.custcode = accountNumber;  //客户编码
                cpa.vsalestrucode = swsalescode;//isEquip ? dzsalescode: swsalescode ; //销售组织编码
                cpa.created_by = q.Opportunity.Owner.Name; //创建人名字
                cpa.sub_corp_manager = q.Opportunity.Owner.Manager.Name;  //报价的销售中心总监名字
                //cpa.csourcecode = cp.Contract__r.ContractNumber__c; //合同自动编号
                cpa.ts = Utils.date2string(System.now()) ; //合同的lastmodifieddate
                cpa.cemployeecode = q.Opportunity.Owner.Name; //所有者
                cpa.invcode = qp.Product__r.NCCode__c; //产品的NCCode__c\
                cpa.dreceiptdate  = Utils.date2string(Date.valueOf(System.now()));//报价日期
                cpa.currtypename = '美元';
                if(qp.CooperativePrice__c == null)return qp.Product__r.Name  + '没有价格,不能同步!';
                 cpa.noriginalcurtaxprice = String.valueof(qp.CooperativePrice__c); 
                
               //SalesPrice__c
                cpa.nitemdiscountrate = '100';//默认100
                //cpa.nnumber = String.valueof(cp.Number__c);
                cpa.opertype = '1'; //操作类型   1=新增  2=修改  3=删除
                cpa.quotetype = '1'; //报价类型   1=报价  2=调价
                cpa.csalequotationid = mainId;
                cpa.csalequotation_bid = qp.Id ;
               // cpa.addCustomer =cp.Contract__r.TerminalCustomer__r.NCICCode__c;
                productArgsList.add(cpa);

                 productMap.put(cpa.invcode, cpa);
                if(qp.Product__r.RelatedProducts__c != null){

                    for(String code : qp.Product__r.RelatedProducts__c.split('\\*')){

                        if(code != cpa.invcode){
                           nccodeMap.put(code,cpa.invcode);
                        }
                    }
                }
              
              
          }

            Integer i = 1;
           for(String code : nccodeMap.keySet()){

                if(productMap.containsKey(code))continue;
                ConProductArgs crgs = productMap.get(nccodeMap.get(code));
                ConProductArgs crgs1 = crgs.clone();
                crgs1.csalequotation_bid = i+'-' +crgs1.csalequotation_bid;
                crgs1.invcode = code;
                productArgsList.add(crgs1);
                i ++;

            }

           String msg =  q.WhetherSynchronizeNC__c == true  ?'OK' : sycToNc(productArgsList) ;
             System.debug('QuoteAboardControllerTest==>postOverseaQuote');
          
            if(msg == 'OK'){
              q.WhetherSynchronizeNC__c = true;
               //if(isEquip )q.WhetherSynchronizeNC__c = true;
              // if(!isEquip)q.WhetherRegentSynchronizeNC__c = true ;
                update q;
              String res = q.WhetherReverse__c == false ?  AdjustPriceHandler.adjustAboardQuoteToPriceList(mainId ) : '同步并反写成功!' ;
               
               
                return res;
              
            }else{
              return msg;
            }
     }*/

     public static String sycToNcNew(List<ConProductArgs>data){
         Map<String ,List<ConProductArgs>>temp = new Map<String ,List<ConProductArgs>>();
          temp.put('data',data);

          String body = JSON.serialize(temp);
            System.debug(body);
            HttpRequest req = new HttpRequest();
            req.setBody(body);
            //return body;
            req.setMethod('POST');
            req.setHeader('Content-Type','text/plain');
            // 接口写在自定义标签的quoteUrl里面
            req.setEndpoint(System.Label.quoteUrl);

            System.debug('+++'+ body);
            
            HttpResponse res = Utils.postRequest(req, 1);
             System.debug('+++'+res.getBody());
         
            if (res.getStatusCode() == 200) {
                Map<String,Object> r = new Map<String,Object>();
                //如果是测试
                if(Test.isRunningTest()){

                    Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{\"result_msg\":\"操作成功！\",\"result\":1,\"data\":{\"ts\":\"2018-01-04 16:24:18\"}}');
                    r =  resBody;
                }else{
                     r  = (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
   
                }
               // return res.getBody();
                 if(r.get('code') == 0 || r.get('code') == '0'){
                    Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
                
                    if (rs.get('result') == 1 ) {
                       return res.getBody();
                    }else{
                       throw new DmlException((String) rs.get('result_msg') );
                    }
                    
                   
                 }else{
                     throw new DmlException((String) r.get('msg') );
                 }

                
            } else {
               throw new DmlException(res.toString()+',请联系系统管理员!');
            }

      }
      /*

     public static String sycToNc(List<ConProductArgs>data){
         Map<String ,List<ConProductArgs>>temp = new Map<String ,List<ConProductArgs>>();
          temp.put('data',data);

          String body = JSON.serialize(temp);
            System.debug(body);
            HttpRequest req = new HttpRequest();
            req.setBody(body);
            //return body;
            req.setMethod('POST');
            req.setHeader('Content-Type','text/plain');
            // 接口写在自定义标签的quoteUrl里面
            req.setEndpoint(System.Label.quoteUrl);

            System.debug('+++'+ body);
            
            HttpResponse res = Utils.postRequest(req, 1);
             System.debug('+++'+res.getBody());
         
            if (res.getStatusCode() == 200) {
                Map<String,Object> r = new Map<String,Object>();
                //如果是测试
                if(Test.isRunningTest()){

                    Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{\"result_msg\":\"操作成功！\",\"result\":1,\"data\":{\"ts\":\"2018-01-04 16:24:18\"}}');
                    r =  resBody;
                }else{
                     r  = (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
   
                }
               // return res.getBody();
                 if(r.get('code') == 0 || r.get('code') == '0'){
                  Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
                
                   String msg = '系统提示:';
                   msg +=  rs.get('result') == 0 ? '同步失败:' +(String) rs.get('result_msg')  :'同步成功';
                   if (rs.get('result') == 1 ) {
                      return 'OK';
                   }
                     
                  return msg;
                 }else{
                  return '系统提示:' + (String)r.get('msg') ;
                 }

                return 'OK';
            } else {
                return '系统错误:'+res.toString()+',请联系系统管理员!';
            }
   }
   */
     global class ConProductArgs {
        global String corpcode;  //报价上新增字段 公司编码 报价.corpcode__c
        global String custcode;  //客户的NCAccountNumber__c
        global String vsalestrucode;  //报价上新增字段 销售组织编码 报价.vsalestrucode__c
        global String created_by;  //报价的创建人名字
        global String sub_corp_manager;  //报价的销售中心总监名字
        global String csourcecode;  //报价的QuoteNumber
        global String ts;  //报价的lastmodifieddate
        global String csalequotationid;  //报价的id
        global String csalequotation_bid;  //报价产品的id
        global String cemployeecode;  //报价所有者
        global String invcode;  //报价产品.产品的NCCode__c
        global String noriginalcurtaxprice;  //报价产品的SalesPrice__c
        global String nitemdiscountrate;  //报价产品的DiscountRate__c
        global String nnumber;  //报价产品的Quantity__c
        global String opertype; //操作类型   1=新增  2=修改  3=删除
        global String quotetype; //报价类型   1=报价  2=调价
        global String adjustid; //调价的id
        global String adjust_pid; //调价产品的id
        global String addCustomer; //客户终端类型
        global String currtypename ; //币种
        global String dreceiptdate;//报价日期
        global String  dvalidate;//有效期从

    }
}